package aad.storyboard.model;

import java.util.ArrayList;
import java.util.HashMap;

import android.util.Log;


public class AnimationProvider {
	
	private static AnimationProvider instance = new AnimationProvider();
	
	private HashMap<Integer, ArrayList<Animation>> onEventAnimations;
	private ArrayList<Animation> plannedAnimations;
	private ArrayList<Animation> animationStack;
	public static final int EVENT_TOUCH = 0;
	public static final int EVENT_DRAG = 1;
	public static final int EVENT_SHAKE = 2;
	public static final int EVENT_NONE = 3;
	
	public static AnimationProvider getInstance(){
		return instance;
	}
	
	private AnimationProvider(){
		onEventAnimations = new HashMap<Integer, ArrayList<Animation>>();
		plannedAnimations = new ArrayList<Animation>();
		animationStack = new ArrayList<Animation>();
	}
	
	public void addAnimation(Animation anim, int event){
		if(event == EVENT_NONE && anim.getTime() > -1){
			plannedAnimations.add(anim);
			Log.e("TAG","Added planned animation");
		}
		else if (event == EVENT_TOUCH || event == EVENT_DRAG || event == EVENT_SHAKE){
			Integer key = new Integer(event);
			if(onEventAnimations.containsKey(new Integer(event))){
				onEventAnimations.get(key).add(anim);
			}
			else{
				ArrayList<Animation> list = new ArrayList<Animation>();
				list.add(anim);
				onEventAnimations.put(key, list);
				Log.e("TAG","Added new animation"+event);
			}
		}
		
	}
	
	public void addAnimation(Image img, Animation anim, int event){
		anim.addImage(img);
		this.addAnimation(anim,	 event);
	}
	
	public void addAnimation(ArrayList<Image> images, Animation anim, int event){
		for(Image i : images)
			anim.addImage(i);
		this.addAnimation(anim,	 event);
	}

	public HashMap<Integer, ArrayList<Animation>> getOnEventAnimations() {
		return onEventAnimations;
	}

	public ArrayList<Animation> getPlannedAnimations() {
		return plannedAnimations;
	}
	
	public void addAnimationToStack(Animation a){
		animationStack.add(0,a);
	}
	
	public void undoMostRecentAnimationOfStack(){
		if(animationStack.size()< 1)
			return;
		Animation a = animationStack.get(0);
		a.stop();
		a.undo();
		animationStack.remove(0);
	}
	
	public int getMostRecentAnimationTime(){
		if(animationStack.size()< 1)
			return -1;
		return animationStack.get(0).getTime();
	}
	
	public void undoAllAnimationsBackToTime(int time){
		if(animationStack.size()< 1)
			return;
		Animation a = animationStack.get(0);
		while(a.getTime() >= time){
			a.stop();
			a.undo();
			animationStack.remove(0);
			a = animationStack.get(0);
		}
	}
	
	public void stopAllActiveAnimations(){
		for(Animation a : this.animationStack){
			if(a.isActive()){
				a.stop();
			}
		}
	}
	
	public void pauseAllActiveAnimations(){

		for(Animation a : this.animationStack){
			if(a.isActive()){
				a.pause();
			}
		}
	}

	public void unpauseAllAnimations() {
		for(Animation a : animationStack){
			if(a.getState().equals(AnimationStatePaused.getInstance()))
				a.start();
		}
	}
}
